package com.xiaoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoyi.entity.*;
import com.xiaoyi.service.SysRoleMenuService;
import com.xiaoyi.service.SysRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 小易
 * @version 1.0
 * @description TODO
 * @date 2022/12/16 11:01
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Resource
    private SysRoleService roleService;

    @Resource
    private SysRoleMenuService roleMenuService;

    /**
     * @description 添加或修改
     * @param role 角色信息
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 14:06
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add') || hasAuthority('system:role:edit')")
    public ResultBody save(@RequestBody SysRole role){
        if (role.getId() == null || role.getId() == -1){
            role.setCreateTime(new Date());
            roleService.save(role);
        }else {
            role.setUpdateTime(new Date());
            roleService.updateById(role);
        }
        return ResultBody.success();
    }

    /**
     * @description 更新角色的权限列表
     * @param roleId 角色id
     * @param menuIds 新菜单权限id列表
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 15:16
     */
    @Transactional
    @PostMapping("/updateMenus/{roleId}")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public ResultBody updateMenus(@PathVariable("roleId") Long roleId,@RequestBody Long[] menuIds){
        List<SysRoleMenu> roleMenuList = new ArrayList<>();
        for (Long menuId : menuIds) {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuList.add(roleMenu);
        }
        roleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
        roleMenuService.saveBatch(roleMenuList);
        return ResultBody.success();
    }

    /**
     * @description 批量删除
     * @param ids id列表
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 14:18
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public ResultBody delete(@RequestBody Long[] ids){
        roleService.removeByIds(Arrays.asList(ids));
        roleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", ids));
        return ResultBody.success();
    }

    /**
     * @description 分页查询角色
     * @param pageBean 分页
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 13:41
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResultBody list(PageBean pageBean){
        String query = pageBean.getQuery();
        Page<SysRole> page = roleService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), new QueryWrapper<SysRole>().like(StringUtils.hasText(query),"name",query));
        List<SysRole> roleList = page.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", roleList);
        resultMap.put("total", page.getTotal());
        return ResultBody.success(resultMap);
    }

    /**
     * @description 根据id查询
     * @param id 角色id
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 14:07
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResultBody findById(@PathVariable("id") Integer id){
        SysRole role = roleService.getById(id);
        return ResultBody.success(role);
    }

    /**
     * @description 查询所有角色
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 15:03
     */
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('system:role:query')")
    public ResultBody listAll(){
        List<SysRole> roleList = roleService.list();
        return ResultBody.success(roleList);
    }

    /**
     * @description 查询某一角色的菜单列表
     * @param id 角色id
     * @return com.xiaoyi.entity.ResultBody
     * @author 小易
     * @date 2022/12/16 15:03
     */
    @GetMapping("/menus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public ResultBody getMenusById(@PathVariable("id") Integer id){
        List<SysRoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        return ResultBody.success(menuIdList);
    }

}
